import os
import argparse
from PyPDF2 import PdfReader, PdfWriter
from PIL import Image, ImageFilter, ImageDraw
import pdf2image
import random

def apply_scaneffect(image):
    """应用扫描效果到图像上"""
    # 添加噪点
    draw = ImageDraw.Draw(image)
    width, height = image.size
    for _ in range(int(width * height * 0.05)):  # 控制噪点数量
        x = random.randint(0, width - 1)
        y = random.randint(0, height - 1)
        draw.point((x, y), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    
    # 应用模糊效果
    image = image.filter(ImageFilter.GaussianBlur(radius=1))
    
    # 转换为灰度
    image = image.convert('L')
    
    return image

def convert_pdf_to_scanned_style(inputpdf, outputpdf):
    """将PDF转换为扫描样式"""
    # 将PDF的每一页转换为图像
    images = pdf2image.convert_from_path(inputpdf)

    # 对每张图像应用扫描效果
    scanned_images = [apply_scaneffect(image) for image in images]

    # 保存修改后的图像为PDF
    scanned_images[0].save(outputpdf, save_all=True, append_images=scanned_images[1:])

if __name__ == "__main__":
    # 设置命令行参数
    parser = argparse.ArgumentParser(description='Convert a PDF to a scanned style PDF.')
    parser.add_argument('inputpdf', type=str, help='The input PDF file path')
    parser.add_argument('outputpdf', type=str, help='The output PDF file path')
    
    args = parser.parse_args()
    
    # 调用函数
    convert_pdf_to_scanned_style(args.inputpdf, args.outputpdf)
